package com.hsgene.order.controller.applets;

import com.hsgene.common.RangeType;
import com.hsgene.common.exception.CommonErrorCode;
import com.hsgene.common.util.exception.ErrorCode;
import com.hsgene.common.util.qiniu.QiniuCertificateUtil;
import com.hsgene.common.util.resolver.FromSession;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.web.session.UserInfo;
import com.hsgene.order.domain.v1.GeneticInvoice;
import com.hsgene.order.exception.OrderErrorCode;
import com.hsgene.order.service.GeneticInvoiceService;
import com.hsgene.order.service.api.GeneratorService;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description:
 * @projectName: hdas-geneshop-server
 * @package: com.hsgene.order.controller.app
 * @author: maodi
 * @createDate: 2018/10/11 15:42
 * @version: 1.0
 * Copyright: Copyright (c) 2018
 */
@RestController
@RequestMapping("/v1.0/genetic/testing/invoices")
public class GeneticInvoiceController {

    private static Logger LOGGER = LogManager.getLogger(GeneticInvoiceController.class);

    @Resource
    GeneticInvoiceService geneticInvoiceService;

    @Resource
    GeneratorService generatorService;

    /**
     * @param userInfo 用户信息
     * @return com.hsgene.common.util.result.ApiResult
     * @description 根据用户id获取发票列表
     * @author maodi
     * @createDate 2018/10/11 16:15
     */
    @GetMapping
    public ApiResult<List<GeneticInvoice>> getGeneticInvoiceList(@FromSession UserInfo userInfo) {
        try {
            if (userInfo == null) {
                return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            List<GeneticInvoice> list = geneticInvoiceService.getGeneticInvoiceByUserId(userId);
            //图片加签
            for (GeneticInvoice invoice : list) {
                String oldUrl = invoice.getEnterpriseSealVoucher();
                String newUrl = QiniuCertificateUtil.getDownloadCertificateStr(oldUrl);
                invoice.setEnterpriseSealVoucher(newUrl);
            }
            list.sort((GeneticInvoice o1, GeneticInvoice o2) -> o2.getIsDefault() - o1.getIsDefault());
            return ApiResult.succ(list);
        } catch (Exception e) {
            LOGGER.error(OrderErrorCode.GET_INVOICE_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrderErrorCode.GET_INVOICE_IS_ERROR);
        }
    }

    /**
     * @param geneticInvoice 发票信息
     * @param userInfo       用户信息
     * @return com.hsgene.common.util.result.ApiResult
     * @description 新增发票信息
     * @author maodi
     * @createDate 2018/10/11 16:16
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @PostMapping
    public ApiResult<NullObject> insertGeneticInvoice(
            @RequestBody GeneticInvoice geneticInvoice,
            @FromSession UserInfo userInfo) {
        try {
            if (userInfo == null) {
                return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(OrderErrorCode.USER_ID_IS_NULL);
            }
            geneticInvoice.setUserId(userId);
            ErrorCode code = checkGeneticInvoice(geneticInvoice, null);
            if (code != null) {
                return ApiResult.fail(code);
            }
            String id = generatorService.getGenerator("", "").getData().getSerialNumber();
            geneticInvoice.setId(id);
            geneticInvoiceService.insertGeneticInvoice(geneticInvoice);
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(OrderErrorCode.INSERT_INVOICE_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrderErrorCode.INSERT_INVOICE_IS_ERROR);
        }
    }

    /**
     * @param geneticInvoice 发票信息
     * @param id             发票id
     * @return com.hsgene.common.util.exception.ErrorCode
     * @description 验证发票信息是否合格
     * @author maodi
     * @createDate 2018/10/11 17:49
     */
    private ErrorCode checkGeneticInvoice(GeneticInvoice geneticInvoice, String id) {
        if (geneticInvoice == null) {
            return OrderErrorCode.INVOICE_IS_NULL;
        }
        String userId = geneticInvoice.getUserId();
        String personName = geneticInvoice.getPersonName();
        String companyName = geneticInvoice.getCompanyName();
        //判断个人名称和单位名称是否都为空
        if (StringUtils.isBlank(personName) && StringUtils.isBlank(companyName)) {
            return OrderErrorCode.NAME_IS_NULL;
        }
        //判断个人名称是否存在
        if (StringUtils.isNotBlank(personName)) {
            //如果个人名称存在则单位名称和纳税号都设置为空字符串
            geneticInvoice.setCompanyName("");
            geneticInvoice.setTaxesNo("");
            int personNameCount = geneticInvoiceService.getCountByPersonNameAndUserId(personName, userId, id);
            if (personNameCount > 0) {
                return OrderErrorCode.PERSON_NAME_IS_EXIST;
            }
        }
        //判断单位名称是否存在
        else if (StringUtils.isNotBlank(companyName)) {
            int companyNameCount = geneticInvoiceService.getCountByCompanyNameAndUserId(companyName, userId, id);
            if (companyNameCount > 0) {
                return OrderErrorCode.COMPANY_NAME_IS_EXIST;
            }
            String taxesNo = geneticInvoice.getTaxesNo();
            if (StringUtils.isBlank(taxesNo)) {
                return OrderErrorCode.TAXES_NO_IS_NULL;
            }
            if (taxesNo.length() != 15 && taxesNo.length() != 18 && taxesNo.length() != 20) {
                return OrderErrorCode.TAXES_NO_IS_NON_CONFORMITY;
            }
            //单位名称需要有企业盖章凭
            String enterpriseSealVoucher = geneticInvoice.getEnterpriseSealVoucher();
            if (StringUtils.isBlank(enterpriseSealVoucher)) {
                return OrderErrorCode.ENTERPRISE_SEAL_VOUCHER_IS_NULL;
            }
        }
        String remarks = geneticInvoice.getRemarks();
        //判断备注是否超过200字符
        if (StringUtils.isNotBlank(remarks)) {
            if (remarks.length() > 200) {
                return OrderErrorCode.REMARKS_IS_EXCEED_200;
            }
        }
        //判断发票类型
        Integer invoiceType = geneticInvoice.getInvoiceType();
        if (invoiceType == null) {
            return OrderErrorCode.INVOICE_TYPE_IS_NULL;
        }
        if (invoiceType != 0 && invoiceType != 1) {
            return OrderErrorCode.INVOICE_TYPE_IS_ERROR;
        }
        return null;
    }

    /**
     * @param geneticInvoice 发票信息
     * @param userInfo       用户信息
     * @param rangeType      范围类型
     * @param invoiceId      发票id
     * @return com.hsgene.common.util.result.ApiResult
     * @description 修改发票信息
     * @author maodi
     * @createDate 2018/10/11 16:17
     */
    @PutMapping("{invoice_id}")
    public ApiResult<List<GeneticInvoice>> updateGeneticInvoice(
            @RequestBody(required = false) GeneticInvoice geneticInvoice,
            @FromSession UserInfo userInfo,
            @RequestParam("range_type") String rangeType,
            @PathVariable("invoice_id") String invoiceId) {
        try {
            if (userInfo == null) {
                return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            if (StringUtils.isBlank(rangeType)) {
                return ApiResult.fail(CommonErrorCode.RANGE_TYPE_IS_NULL);
            }
            //修改当前用户其他发票信息为未默认，此发票为默认
            if (RangeType.PART.getMessage().equals(rangeType)) {
                if (StringUtils.isBlank(invoiceId)) {
                    return ApiResult.fail(OrderErrorCode.INVOICE_ID_IS_NULL);
                }
                geneticInvoiceService.updateGeneticInvoiceToDefault(invoiceId, userId);
            } else if (RangeType.ALL.getMessage().equals(rangeType)) {
                geneticInvoice.setUserId(userId);
                ErrorCode code = checkUpdateGeneticInvoice(geneticInvoice);
                if (code != null) {
                    return ApiResult.fail(code);
                }
                geneticInvoiceService.updateGeneticInvoice(geneticInvoice);
            } else {
                return ApiResult.fail(CommonErrorCode.RANGE_TYPE_IS_ERROR);
            }
            List<GeneticInvoice> list = geneticInvoiceService.getGeneticInvoiceByUserId(userId);
            //图片加签
            for (GeneticInvoice invoice : list) {
                String oldUrl = invoice.getEnterpriseSealVoucher();
                String newUrl = QiniuCertificateUtil.getDownloadCertificateStr(oldUrl);
                invoice.setEnterpriseSealVoucher(newUrl);
            }
            list.sort((GeneticInvoice o1, GeneticInvoice o2) -> o2.getIsDefault() - o1.getIsDefault());
            return ApiResult.succ(list);
        } catch (Exception e) {
            LOGGER.error(OrderErrorCode.UPDATE_INVOICE_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrderErrorCode.UPDATE_INVOICE_IS_ERROR);
        }
    }

    /**
     * @param geneticInvoice 发票信息
     * @return com.hsgene.common.util.exception.ErrorCode
     * @description 检查更新发票的信息是否合格
     * @author maodi
     * @createDate 2018/10/11 17:53
     */
    private ErrorCode checkUpdateGeneticInvoice(GeneticInvoice geneticInvoice) {
        if (geneticInvoice == null) {
            return OrderErrorCode.INVOICE_IS_NULL;
        }
        String id = geneticInvoice.getId();
        if (StringUtils.isBlank(id)) {
            return OrderErrorCode.INVOICE_ID_IS_NULL;
        }
        return checkGeneticInvoice(geneticInvoice, id);
    }

    /**
     * @param userInfo  用户信息
     * @param invoiceId 发票id
     * @return com.hsgene.common.util.result.ApiResult
     * @description 根据发票id删除发票信息
     * @author maodi
     * @createDate 2018/10/11 16:18
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @DeleteMapping("{invoice_id}")
    public ApiResult<NullObject> deleteGeneticInvoice(
            @FromSession UserInfo userInfo,
            @PathVariable("invoice_id") String invoiceId) {
        try {
            if (userInfo == null) {
                return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            if (StringUtils.isBlank(invoiceId)) {
                return ApiResult.fail(OrderErrorCode.INVOICE_ID_IS_NULL);
            }
            GeneticInvoice geneticInvoice = geneticInvoiceService.getGeneticInvoiceById(userId, invoiceId);
            if (geneticInvoice == null || StringUtils.isBlank(geneticInvoice.getId())) {
                return ApiResult.fail(OrderErrorCode.HAVE_BEEN_DELETED);
            }
            geneticInvoiceService.deleteGeneticInvoiceById(invoiceId);
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(OrderErrorCode.DELETE_INVOICE_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrderErrorCode.DELETE_INVOICE_IS_ERROR);
        }
    }

    /**
     * @param userInfo  用户信息
     * @param invoiceId 发票id
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.order.domain.v1.GeneticInvoice>
     * @description 根据id获取发票（选择发票）
     * @author maodi
     * @createDate 2018/10/16 16:40
     */
    @GetMapping("{invoice_id}")
    public ApiResult<GeneticInvoice> getGeneticInvoiceById(
            @FromSession UserInfo userInfo,
            @PathVariable("invoice_id") String invoiceId) {
        try {
            if (userInfo == null) {
                return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            if (StringUtils.isBlank(invoiceId)) {
                return ApiResult.fail(OrderErrorCode.INVOICE_ID_IS_NULL);
            }
            GeneticInvoice geneticInvoice = geneticInvoiceService.getGeneticInvoiceById(userId, invoiceId);
            //图片加签
            String oldUrl = geneticInvoice.getEnterpriseSealVoucher();
            String newUrl = QiniuCertificateUtil.getDownloadCertificateStr(oldUrl);
            geneticInvoice.setEnterpriseSealVoucher(newUrl);
            if (geneticInvoice == null || geneticInvoice.getId() == null) {
                return ApiResult.succ(geneticInvoice, "没有找到该id的发票信息");
            }
            return ApiResult.succ(geneticInvoice);
        } catch (Exception e) {
            LOGGER.error(OrderErrorCode.GET_GENETIC_INVOICE_BY_ID_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrderErrorCode.GET_GENETIC_INVOICE_BY_ID_IS_ERROR);
        }
    }

}
